package com.demo.apparel.service.uniapp.Impl;

import com.demo.apparel.entity.Category;
import com.demo.apparel.entity.Clothes;
import com.demo.apparel.entity.ClothesType;
import com.demo.apparel.mapper.uniapp.WxCategoryMapper;
import com.demo.apparel.mapper.uniapp.WxClothesMapper;
import com.demo.apparel.mapper.uniapp.WxClothesTypeMapper;
import com.demo.apparel.service.uniapp.ClothesBrowseService;
import com.demo.apparel.vo.ClothesCategoryVO;
import com.demo.apparel.vo.ClothesSubCategoryVO;
import com.demo.apparel.vo.PageVO;
import com.demo.apparel.vo.uniapp.CategoryBrowseVO;
import com.demo.apparel.vo.uniapp.ClothesGroupVO;
import com.demo.apparel.vo.uniapp.SimpleClothesVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ClothesBrowseServiceImpl implements ClothesBrowseService {

    private final WxClothesMapper clothesMapper;
    private final WxCategoryMapper categoryMapper;

    @Autowired
    private WxClothesTypeMapper wxClothesTypeMapper;

    /**
     * 获取所有用户上传过的衣物数据
     * @return
     */
    @Override
    public List<ClothesCategoryVO> getClothesGroupedByCategory() {
        List<Category> categories = categoryMapper.selectAllCategories();
        List<ClothesCategoryVO> result = new ArrayList<>();

        for (Category category : categories) {
            ClothesCategoryVO vo = new ClothesCategoryVO();
            vo.setId(category.getId());
            vo.setCategoryName(category.getCategoryName());

            List<ClothesSubCategoryVO> typeList = new ArrayList<>();

            // 先“全部”
            ClothesSubCategoryVO all = new ClothesSubCategoryVO();
            all.setIndexId(0);
            all.setName("全部");
            all.setTotal(clothesMapper.countAllByCategory(category.getCategory()));
            all.setClothes(clothesMapper.selectAllClothesByCategory(category.getCategory()));
            typeList.add(all);

            // 取当前大类对应的clothes_type列表
            List<ClothesType> clothesTypes = wxClothesTypeMapper.selectByCategory(category.getCategory());

            int index = 1;
            for (ClothesType type : clothesTypes) {
                ClothesSubCategoryVO sub = new ClothesSubCategoryVO();
                sub.setIndexId(index++);
                sub.setName(type.getTypeName());

                // 判断数据库中是否有该类别name对应的衣服，如果没有则给空数组
                int total = clothesMapper.countClothesByCategoryAndName(category.getCategory(), type.getTypeName());
                sub.setTotal(total);

                if (total > 0) {
                    sub.setClothes(clothesMapper.selectClothesByCategoryAndName(category.getCategory(), type.getTypeName()));
                } else {
                    sub.setClothes(new ArrayList<>());
                }

                typeList.add(sub);
            }

            vo.setType(typeList);
            result.add(vo);
        }

        return result;
    }


    private List<SimpleClothesVO> convertToVO(List<Clothes> list) {
        List<SimpleClothesVO> res = new ArrayList<>();
        for (Clothes item : list) {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(item.getId());
            vo.setDescription(item.getDescription());
            vo.setImage(item.getImageUrl());

            res.add(vo);
        }
        return res;
    }

    /**
     * 搜索功能get
     */
    @Override
    public List<SimpleClothesVO> searchUserClothes(String userId, String keyword, String season) {
        List<Clothes> list = clothesMapper.searchClothesByUserAndKeyword(userId, keyword, season);
        return convertToVO(list);
    }
    /**
     *实现分类搜索查询
     * @param userId
     * @param keyword
     * @param season
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageVO<SimpleClothesVO> searchUserClothesPage(String userId, String keyword, String season, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        // 先查实体列表
        List<Clothes> list = clothesMapper.searchClothesByPage(userId, keyword, season, pageSize, offset);
        int total = clothesMapper.countSearchClothes(userId, keyword, season);
        List<ClothesType> clothesTypes = wxClothesTypeMapper.selectAll(); // 你需要写这个方法
        Map<String, ClothesType> typeMap = clothesTypes.stream()
                .collect(Collectors.toMap(ClothesType::getTypeName, Function.identity()));

        List<SimpleClothesVO> voList = new ArrayList<>();
        for (Clothes item : list) {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(item.getId());
            vo.setDescription(item.getDescription());
            vo.setImage(item.getImageUrl());
            vo.setSeason(item.getSeason());

            // 根据衣服的name，查对应的类型信息
            ClothesType typeInfo = typeMap.get(item.getName());
            if (typeInfo != null) {
                vo.setTypeName(typeInfo.getTypeName());
                vo.setKeywords(typeInfo.getKeywords());
            }

            voList.add(vo);
        }

        return new PageVO<>(voList, total, pageNum, pageSize);
    }


    /**
     * 获取当前用户上传的数据
     */
    @Override
    public List<CategoryBrowseVO> getUserClothesByCategory(String userId) {
        List<Category> categories = categoryMapper.selectAllCategories();
        List<CategoryBrowseVO> result = new ArrayList<>();

        for (Category category : categories) {
            Integer categoryCode = category.getCategory();

            List<ClothesType> clothesTypes = wxClothesTypeMapper.selectByCategory(categoryCode);
            Map<String, ClothesType> typeMap = clothesTypes.stream()
                    .collect(Collectors.toMap(ClothesType::getTypeName, ct -> ct));

            List<ClothesGroupVO> types = new ArrayList<>();

            List<Clothes> allClothes = clothesMapper.selectAllByCategory(userId, categoryCode);
            ClothesGroupVO allGroup = new ClothesGroupVO();
            allGroup.setIndexId(0);
            allGroup.setName("全部");
            allGroup.setTotal(allClothes.size());
            allGroup.setClothes(convertToVOs(allClothes, typeMap));
            types.add(allGroup);

            int index = 1;
            for (ClothesType type : clothesTypes) {
                List<Clothes> matchedClothes = clothesMapper.selectByCategoryAndSubName(userId, categoryCode, type.getTypeName());

                ClothesGroupVO group = new ClothesGroupVO();
                group.setIndexId(index++);
                group.setName(type.getTypeName());
                group.setTotal(matchedClothes.size());
                group.setClothes(convertToVOs(matchedClothes, typeMap));
                types.add(group);
            }

            result.add(new CategoryBrowseVO(category.getId(), category.getCategoryName(), types));
        }

        return result;
    }

    private List<SimpleClothesVO> convertToVOs(List<Clothes> clothesList, Map<String, ClothesType> typeMap) {
        List<SimpleClothesVO> voList = new ArrayList<>();
        for (Clothes c : clothesList) {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(c.getId());
            vo.setDescription(c.getDescription());
            vo.setImage(c.getImageUrl());
            vo.setSeason(c.getSeason());

            ClothesType typeInfo = typeMap.get(c.getName());
            if (typeInfo != null) {
                vo.setTypeName(typeInfo.getTypeName());
                vo.setKeywords(typeInfo.getKeywords());
            }
            voList.add(vo);
        }
        return voList;
    }


    /**
     *
     * @param keyword
     * @param description
     * @param season
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageVO<SimpleClothesVO> searchAllUsersClothesPage(String keyword, String description, String season, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        List<Clothes> list = clothesMapper.searchAllClothesByPage(keyword, description, season, pageSize, offset);
        int total = clothesMapper.countAllSearchClothes(keyword, description, season);

        List<ClothesType> clothesTypes = wxClothesTypeMapper.selectAll();
        Map<String, ClothesType> typeMap = clothesTypes.stream()
                .collect(Collectors.toMap(ClothesType::getTypeName, Function.identity()));

        List<SimpleClothesVO> voList = new ArrayList<>();
        for (Clothes item : list) {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(item.getId());
            vo.setDescription(item.getDescription());
            vo.setImage(item.getImageUrl());
            vo.setSeason(item.getSeason());

            ClothesType typeInfo = typeMap.get(item.getName());
            if (typeInfo != null) {
                vo.setTypeName(typeInfo.getTypeName());
                vo.setKeywords(typeInfo.getKeywords());
            }
            voList.add(vo);
        }

        return new PageVO<>(voList, total, pageNum, pageSize);
    }


    @Override
    public PageVO<SimpleClothesVO> searchUserClothesPagees(
            String userId, String keyword, String description, String season, int pageNum, int pageSize) {

        int offset = (pageNum - 1) * pageSize;
        List<Clothes> list = clothesMapper.searchClothesByPages(userId, keyword, description, season, pageSize, offset);
        int total = clothesMapper.countSearchClotheses(userId, keyword, description, season);

        // 获取类型映射
        List<ClothesType> clothesTypes = wxClothesTypeMapper.selectAll();
        Map<String, ClothesType> typeMap = clothesTypes.stream()
                .collect(Collectors.toMap(ClothesType::getTypeName, Function.identity()));

        List<SimpleClothesVO> voList = new ArrayList<>();
        for (Clothes item : list) {
            SimpleClothesVO vo = new SimpleClothesVO();
            vo.setId(item.getId());
            vo.setDescription(item.getDescription());
            vo.setImage(item.getImageUrl());
            vo.setSeason(item.getSeason());

            ClothesType typeInfo = typeMap.get(item.getName());
            if (typeInfo != null) {
                vo.setTypeName(typeInfo.getTypeName());
                vo.setKeywords(typeInfo.getKeywords());
            }

            voList.add(vo);
        }

        return new PageVO<>(voList, total, pageNum, pageSize);
    }
}
